package org.king.controller.auth;


import javafx.fxml.FXML;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import org.king.MainApplication;
import org.king.service.UserService;
import org.king.util.AlertUtil;
import org.king.util.StringUtil;
import org.springframework.stereotype.Controller;

@Controller
public class LoginController {

    private final UserService userService;
    // 通过构造函数注入（推荐）
    public LoginController(UserService userService) {
        this.userService = userService;
    }
    @FXML
    private TextField account; // 账号
    @FXML
    private PasswordField password; // 密码



    @FXML
    private void doLogin() { //登录
        String accountText = account.getText();
        String passwordText = password.getText();
        // 验证输入是否为空
        if (StringUtil.isEmpty(accountText)) {
            AlertUtil.showAlert(AlertType.ERROR, "登录错误", "账号不能为空", "请输入您的账号");
            account.requestFocus(); // 将焦点设置到账号输入框
            return;
        }

        if (StringUtil.isEmpty(passwordText)) {
            AlertUtil.showAlert(AlertType.ERROR, "登录错误", "密码不能为空", "请输入您的密码");
            password.requestFocus(); // 将焦点设置到密码输入框
            return;
        }
        // 登录
        if (userService.loginUser(accountText,passwordText)) {
            MainApplication.changeView("/view/main-view.fxml");
        } else {
            AlertUtil.showAlert(AlertType.ERROR, "登录失败", "账号或密码错误", "请检查您的账号和密码是否正确");
            // 清空密码框
            password.clear();
            password.requestFocus();
        }
    }

    @FXML
    private void doRegister() {
        // 这里可以跳转到注册界面
        MainApplication.changeView("/view/auth/register-view.fxml");
    }
}
